import { ref } from "vue";
import { calc2pointDistance } from "/@/utils/draw";
import type { PipePathPoint, Point } from "/@/components/types";

/**
 * 拖动路径顶点进入可连接的设备时，所产生的连接UI效果以及连接处理的逻辑
 */
export function useConnEffect({
  getConnectPoints,
  getDraggingRect,
  setDragInfo,
}: {
  getConnectPoints: () => Point[];
  getDraggingRect: () => PipePathPoint | null | undefined;
  setDragInfo: (index?: number) => void;
}) {
  const curConnectPoint = ref<Point | null>(null);
  let connectPoints: Point[] | null = null;
  const opacity = ref(1);
  function mouseover() {
    if (getDraggingRect()) {
      opacity.value = 0.6;
      connectPoints = getConnectPoints();
    }
  }
  function mouseout() {
    if (getDraggingRect()) {
      opacity.value = 1;
      curConnectPoint.value = null;
      connectPoints = null;
    }
  }
  function mousemove() {
    const rect = getDraggingRect();
    if (rect && connectPoints) {
      let targetPoint: Point | null = null;
      let d;
      connectPoints.forEach((p, i) => {
        const distance = calc2pointDistance(rect as Point, p);
        if (!d || d > distance) {
          d = distance;
          targetPoint = p;
        }
      });
      if (targetPoint) {
        curConnectPoint.value = targetPoint;
      }
    }
  }
  function mouseup() {
    const rect = getDraggingRect();
    if (rect && connectPoints) {
      let d;
      let targetPoint: Point | null = null;
      let connectPositionIndex = 0;
      connectPoints.forEach((p, i) => {
        const distance = calc2pointDistance(rect as Point, p);
        if (!d || d > distance) {
          d = distance;
          targetPoint = p;
          connectPositionIndex = i;
        }
      });
      if (targetPoint) {
        rect.x = (targetPoint as Point).x;
        rect.y = (targetPoint as Point).y;
        setDragInfo(connectPositionIndex);
      }
      opacity.value = 1;
      curConnectPoint.value = null;
      connectPoints = null;
    }
  }
  return {
    mouseover,
    mouseout,
    mousemove,
    mouseup,
    curConnectPoint,
    opacity,
  };
}
